package MyJava;

import Entity.DataDTO1;
import Entity.DataDTO2;
import Entity.DataDTO3;
import httpclient.QuickStart;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import HttpServlet.joinmessage;

@WebServlet("/login/dgut")
public class dgut extends HttpServlet {
 protected void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws IOException {
  String token = request.getParameter("token");

  String userip = request.getLocalAddr();
  DataDTO1 dataDTO1 = new DataDTO1(token, "javaee", "b3b52e43ccfd", userip);

  String s1 = QuickStart.postJson("https://cas.dgut.edu.cn/ssoapi/v2/checkToken", dataDTO1);

  Jsonb jsonb = JsonbBuilder.create();
  DataDTO2 dataDTO2 = jsonb.fromJson(s1, DataDTO2.class);

  if (dataDTO2.getMessage()!=null&&dataDTO2.getMessage().equals("success")) {
   List<NameValuePair> list = new ArrayList<>();
   list.add(new BasicNameValuePair("access_token", dataDTO2.getAccess_token()));
   list.add(new BasicNameValuePair("openid", dataDTO2.getOpenid()));


   String s2 = QuickStart.post("https://cas.dgut.edu.cn/oauth/getUserInfo", list);
   if(s2!=null&&s2=="{\n" +
           "\"error\":1,\n" +
           "\"message\":\"access-token不存在或已过期\"\n" +
           "}")
   {
    System.out.println("access-token不存在或已过期");
   }
   else {
    DataDTO3 dataDTO3 = jsonb.fromJson(s2, DataDTO3.class);

    joinmessage.join_message(dataDTO3,request,response);
   }
  }
  else{
   System.out.println(dataDTO2.getMessage());
  }
 }
}
